<template>
    <el-form
      ref="formRef"
      :model="inner"
      :rules="rules"
      label-width="96px"
      @submit.prevent
    >
      <el-row :gutter="16">
        <!-- 父节点选择（级联） -->
        <el-col :span="12">
          <el-form-item label="新父节点">
            <el-cascader
              v-model="parentPath"
              :props="cProps"
              clearable
              filterable
              placeholder="选择父节点（可选根）"
              style="min-width: 360px"
            />
          </el-form-item>
        </el-col>
  
        <el-col :span="12">
          <el-form-item label="当前父节点">
            <el-input :model-value="parentPathText(inner.parentId)" disabled />
          </el-form-item>
        </el-col>
  
        <!-- 编码 / 名称 -->
        <el-col :span="12">
          <el-form-item label="设备编码" prop="code">
            <el-input v-model="inner.code" placeholder="必填" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="设备名称" prop="name">
            <el-input v-model="inner.name" />
          </el-form-item>
        </el-col>
  
        <!-- 设备类型 -->
        <el-col :span="6">
          <el-form-item label="设备类型" prop="nodeType">
            <el-select-v2
              v-model="inner.nodeType"
              :options="typeOptions"
              placeholder="请选择设备类型"
              clearable
              filterable
            />
          </el-form-item>
        </el-col>
  
        <!-- 备件多选 -->
        <el-col :span="6">
          <el-form-item label="备件名称">
            <el-select-v2
              v-model="inner.spareIds"
              :options="spareOptions"
              placeholder="可多选"
              multiple
              collapse-tags
              collapse-tags-tooltip
              filterable
              clearable
              style="width: 100%"
            />
          </el-form-item>
        </el-col>
  
        <!-- 归属部门 -->
        <el-col :span="6">
          <el-form-item label="归属部门" prop="deptId">
            <el-tree-select
              v-model="inner.deptId"
              :data="deptOptions"
              :props="{ value: 'id', label: 'label', children: 'children' }"
              value-key="id"
              placeholder="请选择归属部门"
              check-strictly
            />
          </el-form-item>
        </el-col>
  
        <!-- 特种 / 状态 -->
        <el-col :span="6">
          <el-form-item label="特种设备">
            <el-select v-model.number="inner.isSpecial" placeholder="请选择类型" clearable>
              <el-option label="是" :value="1" />
              <el-option label="否" :value="0" />
            </el-select>
          </el-form-item>
        </el-col>
  
        <el-col :span="8">
          <el-form-item label="设备状态" prop="status">
            <el-select v-model.number="inner.status" placeholder="请选择设备状态">
              <el-option
                v-for="dict in assetNodeStatus"
                :key="dict.value"
                :label="dict.label"
                :value="Number(dict.value)"
              />
            </el-select>
          </el-form-item>
        </el-col>
  
        <!-- 通用文本字段（schema化，增删字段改一行配置即可） -->
        <template v-for="f in textFieldSchema" :key="f.key">
          <el-col :span="12">
            <el-form-item :label="f.label" :prop="f.key">
              <el-input
                v-model="inner[f.key]"
                :maxlength="f.maxlength"
                :show-word-limit="!!f.maxlength"
                :placeholder="f.placeholder || ''"
              />
            </el-form-item>
          </el-col>
        </template>
  
        <!-- 备注 -->
        <el-col :span="24">
          <el-form-item label="备注">
            <el-input v-model="inner.remark" type="textarea" rows="2" />
          </el-form-item>
        </el-col>
      </el-row>
  
      <!-- 操作区：默认放这，也支持外部用 slot 覆盖 -->
      <div class="form-actions" v-if="!$slots.actions">
        <el-button @click="$emit('cancel')">取消</el-button>
        <el-button type="primary" @click="submit">保存</el-button>
      </div>
      <slot name="actions"></slot>
    </el-form>
  </template>
  
  <script setup>
  import { ref, watch,toRaw, isProxy, computed } from 'vue'
  
  const props = defineProps({
    /** edit/create */
    mode: { type: String, default: 'create' },
    /** v-model：表单对象（父传 editForm） */
    modelValue: {
      type: Object,
      default: () => ({
        id: null,
        parentId: null,
        nodeType: 'MODULE',
        name: '',
        code: '',
        remark: '',
        specification: '',
        model: '',
        material: '',
        power: '',
        brand: '',
        manufacturer: '',
        isSpecial: null,
        status: null,
        deptId: null,
        spareIds: [],
      }),
    },
    /** 选项/字典/级联懒加载等 */
    typeOptions: { type: Array, default: () => [] },
    spareOptions: { type: Array, default: () => [] },
    deptOptions: { type: Array, default: () => [] },
    assetNodeStatus: { type: Array, default: () => [] }, // useDict('asset_node_status')
    cProps: { type: Object, required: true }, // 直接复用父的 cascader 配置（含 lazyLoad）
    /** 显示父路径用（父中已有） */
    parentPathText: { type: Function, required: true },
  })
  
  const emit = defineEmits(['update:modelValue', 'submit', 'cancel'])
  
  const formRef = ref()
  const inner = ref(deepCloneSafe(props.modelValue))

  
  // schema：以后加删字段只动这里
  const textFieldSchema = [
    { key: 'specification', label: '设备规格', maxlength: 100 },
    { key: 'model',         label: '设备型号', maxlength: 100 },
    { key: 'material',      label: '设备材质', maxlength: 60  },
    { key: 'power',         label: '设备功率', maxlength: 40,  placeholder:'如 15kW / 3.7kW' },
    { key: 'brand',         label: '设备品牌', maxlength: 60  },
    { key: 'manufacturer',  label: '制造厂家', maxlength: 120 },
  ]
  
  const rules = {
    name: [{ required: true, message: '设备名称必填', trigger: 'blur' }],
    code: [{ required: true, message: '设备编码必填', trigger: 'blur' }],
    nodeType: [{ required: true, message: '请选择类型', trigger: 'change' }],
    specification: [{ max: 100, message: '最多 100 字', trigger: 'blur' }],
    model: [{ max: 100, message: '最多 100 字', trigger: 'blur' }],
    material: [{ max: 60, message: '最多 60 字', trigger: 'blur' }],
    power: [{ max: 40, message: '最多 40 字', trigger: 'blur' }],
    brand: [{ max: 60, message: '最多 60 字', trigger: 'blur' }],
    manufacturer: [{ max: 120, message: '最多 120 字', trigger: 'blur' }],
  }
  
  const parentPath = ref([])
  /** 外部 v-model → 内部 */
  watch(() => props.modelValue, (v) => {
  inner.value = deepCloneSafe(v || {})
}, { deep: true, immediate: true })

  
  /** 内部 → 外部 v-model */
  watch(inner, (v) => emit('update:modelValue', v), { deep: true })
  
  function submit() {
    formRef.value?.validate((ok) => {
      if (!ok) return
      emit('submit', normalize(inner.value))
    })
  }

  // 安全深拷贝：先 toRaw 移除 Proxy，再用 JSON 方案（字段都是可序列化的就足够）
// 如需保留 Date/undefined/BigInt，可换 lodash.cloneDeep
function deepCloneSafe(v) {
  const raw = isProxy(v) ? toRaw(v) : v
  try {
    return JSON.parse(JSON.stringify(raw))
  } catch {
    // 兜底：浅拷贝，避免阻塞
    return { ...raw }
  }
}
  
  /** 规范化输出（去空串、修正类型等） */
  function normalize(v) {
    const out = { ...v }
    // 统一空值
    ;['specification','model','material','power','brand','manufacturer','remark'].forEach(k => {
      if (out[k] == null) out[k] = ''
    })
    if (!Array.isArray(out.spareIds)) out.spareIds = []
    // 这些在父级会用到
    return out
  }
  
  /** 允许父组件手动触发校验 / 取数据 */
  function validate() {
    return formRef.value?.validate()
  }
  function getValue() {
    return normalize(inner.value)
  }
  defineExpose({ validate, getValue })
  
  // 当 parentPath 变化时，同步 parentId
  watch(parentPath, (arr) => {
    inner.value.parentId = Array.isArray(arr) && arr.length ? arr[arr.length - 1] : 0
  })
  </script>
  
  <style scoped>
  .form-actions {
    display: flex;
    justify-content: flex-end;
    gap: 8px;
    margin-top: 12px;
  }
  </style>
  